import numpy as np
import pandas as pd
import os
from word_spell import Document
import docx
from docx.shared import Inches

os.chdir(r"I:\ZCG\02_电子同学录\codes")
if not os.path.exists("./result"):
    os.mkdir("result")

# 数据读取与预处理
raw_file = pd.read_excel("../source/0702_的电子同学录_33_33.xlsx", )
data = raw_file[raw_file.columns[6:-1]]
data["2、您的性别："] = np.where(data[["2、您的性别："]] == 1, "男", "女")
data['12、你想要我给你回写同学录吗？'] .replace(1, "不用了", inplace=True)
data['12、你想要我给你回写同学录吗？'] .replace(2, "那我就勉强接受吧", inplace=True)
data['12、你想要我给你回写同学录吗？'] .replace(3, "想", inplace=True)
data.replace(-3, "跳过", inplace=True)

# 最后一列链接替换为图片的绝对路径
pic_path = r"I:\ZCG\02_电子同学录\source\0702_附件"
pic_list = os.listdir(pic_path) 
for i in range(len(data)):
    name = data.iloc[i, 0]
    for j in range(len(pic_list)):
        if name in pic_list[j]:     # 文件夹中存在XX的照片
            pic_abspath = pic_path + "\\" + pic_list[j]
            data.iloc[i, -1] = pic_abspath

# 读取模板  模板的参数
template = Document("template0.docx")
items = template.get_vars()
data.columns = items

pic_data = data.iloc[:, [0, -1]]
data['介意留张照片吗'] = np.where(data[['介意留张照片吗']] == '(空)', "不了", "不介意")

# 数据写入模板
for i in range(len(data)):
    doc = Document("template0.docx")
    row = data.iloc[i]
    print(row[0], " start")
    doc.render_from_template(
        out=f"result/{row['姓名']}.docx",
        **row
    )

print("write finished")

# 写入照片
pic_doc_path = "./result/pic/"
if not os.path.exists(pic_doc_path):
    os.mkdir(pic_doc_path)

pic_data = pic_data[pic_data['介意留张照片吗'] != '(空)']
for i in range(len(pic_data)):
    name = pic_data.iloc[i]['姓名']
    print(name)
    docx_file = docx.Document("./result/" + name + ".docx")
    docx_file.add_picture(pic_data.iloc[i]['介意留张照片吗'], width=Inches(4))
    docx_file.save(pic_doc_path+ name + "_pic.docx")

print("Finished")
